/**
 * Copyright (C) 2010 DustedPixels.com
 */
package com.dustedpixels.cirt;

import java.awt.Component;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.InputStream;

import javax.swing.JFrame;
import javax.swing.WindowConstants;

import com.dustedpixels.cirt.awt.VideoComponents;
import com.dustedpixels.cirt.awt.VideoImages;
import com.dustedpixels.cirt.model.machine.spectrum.ZxSpectrum48;

/**
 * Zx
 *
 * @author Michal Pociecha-Los (micapolos@gmail.com)
 */
public final class Cirt {
  public static void main(String[] args) throws Exception {
    GraphicsEnvironment graphEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice graphDevice = graphEnv.getDefaultScreenDevice();
    final GraphicsConfiguration graphicConf = graphDevice.getDefaultConfiguration();
    
    JFrame frame = new JFrame("ZX", graphicConf);

    byte[] romBytes = new byte[16384];
    byte[] ram1Bytes = new byte[16384];
    byte[] ram2Bytes = new byte[32768];
    byte[] videoBytes = new byte[352 * 304];

    InputStream inputStream = Cirt.class.getClassLoader().getResourceAsStream("DynamiteDan.scr");
    try {
      for (int i = 0; i < 6912; i++) {
        ram1Bytes[i] = (byte) inputStream.read();
      }
    } finally {
      inputStream.close();
    }
    
    ZxSpectrum48 zx = new ZxSpectrum48(romBytes, ram1Bytes, ram2Bytes, videoBytes);

    byte n = (byte) 0xC0;
    byte b = (byte) 0xFF;
    byte[] redPalette = new byte[] {0, 0, n, n, 0, 0, n, n, 0, 0, b, b, 0, 0, b, b};
    byte[] greenPalette = new byte[] {0, 0, 0, 0, n, n, n, n, 0, 0, 0, 0, b, b, b, b};
    byte[] bluePalette = new byte[] {0, n, 0, n, 0, n, 0, n, 0, b, 0, b, 0, b, 0, b};

    BufferedImage videoImage = VideoImages.newPaletteImage(
        352,
        304, 
        videoBytes,
        redPalette, 
        greenPalette,
        bluePalette);
    
    final Component zxCanvas = VideoComponents.newHeavyweightComponent(
        graphicConf, 
        videoImage);
    
    frame.getContentPane().add(zxCanvas);
    
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(730, 600);
    frame.setVisible(true);
    
    Runnable onRepaint = new Runnable() {
      public void run() {
        zxCanvas.repaint();
      }
    };
    
    Runnable mainLoop = CirtRunnables.newRunnable(onRepaint, zx, videoBytes);
    
    mainLoop.run();
  }
}
